<template>
  <div class="container">
    <div class="header">
      <el-input
        placeholder="请输入菜品名称"
        v-model="input"
        clearable
        @keyup.enter.native="handleSearch"
      >
        <i
          slot="prefix"
          class="el-input__icon el-icon-search"
          @click="handleSearch"
        ></i>
      </el-input>
      <div class="batch-actions">
        <button @click="handleBatchDelete" class="action-button">
          批量删除
        </button>
        <button @click="handleBatchEnable" class="action-button">
          批量起售
        </button>
        <button @click="handleBatchDisable" class="action-button">
          批量停售
        </button>
      </div>
      <el-button
        type="primary"
        round
        icon="el-icon-circle-plus-outline"
        @click="showAddDishDialog"
        >添加菜品</el-button
      >
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      :row-class-name="tableRowClassName"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column prop="name" label="菜品名称"> </el-table-column>
      <el-table-column label="图片">
        <template v-slot="{ row }">
          <img
            :src="`${env}/common/download?name=${row.image}`"
            style="width: 50px; height: 50px; object-fit: cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="category" label="菜品分类"> </el-table-column>
      <el-table-column prop="price" label="售价"> </el-table-column>
      <el-table-column prop="status" label="售卖情况">
        <template v-slot="{ row }">
          <el-tag :type="row.status === '上架' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="tame" label="最后操作时间"> </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <div style="display: flex; gap: 8px">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              type="warning"
              size="mini"
              @click="handleChangeStatus(scope.row)"
              >起售</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[100, 200, 300, 400]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="400"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import { getDishes } from "@/api/dish";

export default {
  data() {
    return {
      env: process.env.VUE_APP_BASE_API,
      input: "",
      pageInfo: {
        page: 1,
        pageSize: 10,
      },
      addDishForm: {
        category: "", // 新菜品的品类
        name: "", // 新菜品的名称
        price: "", // 新菜品的价格
        status: "", // 新菜品的状态
        image: "", // 新菜品的图片
        tame: "", //最后操作时间
      },
      tableData: [],
      pageInfo: {
        page: 1,
        pageSize: 10,
      },
    };
  },
  methods: {
    init() {
      getDishes(this.pageInfo).then((res) => {
        const { total, records } = res.data;
        this.tableData = records;
        this.total = total;
      });
    },
    //搜索
    handleSearch() {
      getDishes({ ...this.pageInfo, name: this.input }).then((res) => {
        const { total, records } = res.data;
        this.tableData = records;
        this.total = total;
      });
    },
    //表格
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    //分页
    handleSizeChange(val) {
      this.pageinfo.page = 1;
      this.pageInfo.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.pageInfo.page = val;
      this.init();
    },
    async handleChangeStatus(row) {
      const res = await changeStatus({ id: row.id, status: +!row.status });
      this.init();
    },
    debounce(func, delay) {
      let timer;
      return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, args);
        }, delay);
      };
    },
    // 获取选中项的 ID
    getSelectedIds() {
      return this.$refs.table.selection.map((row) => row.id);
    },

    // 批量删除
    handleBatchDelete() {
      const ids = this.getSelectedIds();
      if (!ids.length) {
        this.$message.warning("请选择要删除的菜品！");
        return;
      }
      // 调用批量删除接口
      deleteDishBatch(ids).then(() => {
        this.$message.success("批量删除成功！");
        this.init();
      });
    },

    // 批量起售
    handleBatchEnable() {
      const ids = this.getSelectedIds();
      if (!ids.length) {
        this.$message.warning("请选择要起售的菜品！");
        return;
      }
      // 调用批量起售接口
      changeStatusBatch(ids, "上架").then(() => {
        this.$message.success("批量起售成功！");
        this.init();
      });
    },

    // 批量停售
    handleBatchDisable() {
      const ids = this.getSelectedIds();
      if (!ids.length) {
        this.$message.warning("请选择要停售的菜品！");
        return;
      }
      // 调用批量停售接口
      changeStatusBatch(ids, "下架").then(() => {
        this.$message.success("批量停售成功！");
        this.init();
      });
    },
    // 删除菜品功能
    async handleDelete(row) {
      try {
        await deleteDish(row.id); // 调用删除接口
        this.$message.success("删除成功！");
        this.init(); // 重新加载数据
      } catch (error) {
        this.$message.error("删除失败！");
      }
    },
    async handleAddDish() {
      try {
        await addDish(this.addDishForm); // 调用添加接口
        this.$message.success("添加成功！");
        this.showAddDishDialog = false; // 关闭对话框
        this.init(); // 重新加载数据
      } catch (error) {
        this.$message.error("添加失败！");
      }
    },
  },
  created() {
    this.init();
    //包装防抖
    this.debouncedChangeStatus = this.debounced(this.handleChangeStatus, 300);
  },
};
</script>
<style lang="scss" scoped>
.container {
  padding: 50px;
  .header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .el-input {
      width: 250px;
      .el-icon-search {
        cursor: pointer;
      }
    }
  }
  .footer {
    margin-block: 22px;
    display: flex;
    justify-content: center;
  }
  .el-table th,
  .el-table td {
    text-align: center;
    vertical-align: middle;
  }

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
}
.action-button {
  background: none;
  border: none;
  color: #409eff; /* 按钮文字颜色 */
  cursor: pointer;
  padding: 0 10px;
  font-size: 14px;
}

/* 鼠标悬停时效果 */
.action-button:hover {
  text-decoration: underline;
}

/* 按钮容器布局 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions {
  margin-left: auto; /* 让批量操作按钮组靠右对齐 */
  display: flex;
  gap: 8px; /* 按钮之间的间距 */
}
</style>